#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <cstring>
#include <string>
#include "Lock.hpp"
pthread_mutex_t pm = PTHREAD_MUTEX_INITIALIZER;
using namespace std;
int ticket = 1000; // 临界资源
class PthreadData
{
public:
    PthreadData(string name, pthread_mutex_t &key)
        : _name(name),
          _key(key)
    {
    }

public:
    string _name;
    pthread_mutex_t &_key;
};

void *pthreadroutine(void *arg)
{
    // PthreadData *ptr = (PthreadData *)arg;
    PthreadData *ptr = static_cast<PthreadData *>(arg);
    while (1)
    {
        {
            MutexGuard m(&pm);
            // pthread_mutex_lock(&(ptr->_key));
            if (ticket > 0)
            {
                // usleep(1000);
                cout << ptr->_name << ",ticket:" << --ticket << endl;
                // pthread_mutex_unlock(&(ptr->_key));
            }
            else
            {
                // pthread_mutex_unlock(&(ptr->_key));
                break;
            }
        }
        // 买完票继续存储到用户的数据库中。。。
        usleep(1000);
    }
    delete ptr;
    return nullptr;
}

int main()
{
    pthread_t tids[3];
    pthread_mutex_t key;
    pthread_mutex_init(&key, nullptr);
    for (int i = 0; i < 3; i++)
    {
        char name[64];
        snprintf(name, 64, "thread-%d", i + 1);
        PthreadData *ptr = new PthreadData(name, key);
        pthread_create(tids + i, nullptr, pthreadroutine, ptr);
    }
    for (int i = 0; i < 3; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    pthread_mutex_destroy(&key);
    return 0;
}